<?php
    require "config.php";
    $dbh = dbConnect();
    if(isset($_POST["login-submit"])){
        if($_POST["checkbox"]=="remember"){
            if($_POST["username"]!=''){
                $username = $_POST["username"];
                $password = $_POST["password"];
                try{
                    $sql = "select * from users where user_name = '{$username}'";
                    $sth = $dbh->query($sql);
                    $result = $sth->fetch();
                    if($password==$result['user_pwd']){
                        setcookie("username",$username,time()+3600);
                        header("Location:index.php");
                    }else{
                        echo "<script>alert('对不起，密码错误')</script>";
                    }
                }catch(PDOException $e){
                    print("error".$e->getMessage());
                    die();
                }
            }else{
                echo "<script>alert('请输入用户名')</script>";
            }
        }else{
            if($_POST["username"]!=''){
                $username = $_POST["username"];
                $password = $_POST["password"];
                try{
                    $sql = "select * from users where user_name = '{$username}'";
                    $sth = $dbh->query($sql);
                    $result = $sth->fetch();
                    if($password==$result['user_pwd']){
                        setcookie("username","",time()+3600);
                        header("Location:index.php");
                    }else{
                        echo "<script>alert('对不起，密码错误')</script>";
                    }
                }catch(PDOException $e){
                    print("error".$e->getMessage());
                    die();
                }
            }else{
                echo "<script>alert('请输入用户名')</script>";
            }
        }   
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>login</title>
    <link rel="stylesheet" href="./css/login.css">
</head>
<body class="login-body">
    
    <div class="login-form">
        <form action="login.php" method="POST">
            <div class="login-wrap-form" style="text-align: center;"><h1>Login</h1></div>
            <div class="login-wrap-form"><input type="text" class="login-input-text" name="username" value="" placeholder="UserName"></div>
            <div class="login-wrap-form"><input type="text" class="login-input-text" name="password" value="" placeholder="Password"></div>
            <div class="login-wrap-form login-wrap-checkbox"><input type="checkbox" name="checkbox" class="login-input-checkbox" value="remember">Remember me <input type="submit" name="login-submit" value="Login" class="login-input-submit"></div>            
        </form>

        <div class="login-notice">
            <a href="regist.php">前往注册页面</a>
        </div>
    </div>
</body>
</html>